package com.sgb.knowledgeshare.view.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.databinding.DataBindingUtil;
import com.aliyun.common.utils.FileUtils;
import com.aliyun.crop.AliyunCropCreator;
import com.aliyun.crop.struct.CropParam;
import com.aliyun.crop.supply.AliyunICrop;
import com.aliyun.crop.supply.CropCallback;
import com.aliyun.svideo.player.AliyunISVideoPlayer;
import com.aliyun.svideo.player.AliyunSVideoPlayerCreator;
import com.aliyun.svideo.player.PlayerCallback;
import com.aliyun.svideo.sdk.external.struct.common.CropKey;
import com.aliyun.svideo.sdk.external.struct.common.VideoDisplayMode;
import com.aliyun.svideo.sdk.external.struct.common.VideoQuality;
import com.aliyun.svideo.sdk.external.struct.encoder.VideoCodecs;
import com.aliyun.svideo.sdk.external.thumbnail.AliyunIThumbnailFetcher;
import com.aliyun.svideo.sdk.external.thumbnail.AliyunThumbnailFetcherFactory;
import com.duanqu.transcode.NativeParser;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.ActivityShareVideoCompileBinding;
import com.sgb.knowledgeshare.utils.CropOutputParam;
import com.sgb.knowledgeshare.utils.ShareConstants;
import com.sgb.knowledgeshare.view.adapter.VideoTrimAdapter;
import com.sgb.knowledgeshare.weight.HorizontalListView;
import com.sgb.knowledgeshare.weight.SizeChangedNotifier;
import com.sgb.knowledgeshare.weight.VideoSliceSeekBar;
import com.sgb.knowledgeshare.weight.VideoTrimFrameLayout;
import com.swgk.core.base.AppActivity;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import java.lang.ref.SoftReference;
import java.util.ArrayList;

/**
 * Created by：冯齐 on 2020/11/23 18:32
 * Description： 分享-视频编辑
 */
public class ShareVideoCompileActivity extends AppActivity implements TextureView.SurfaceTextureListener, SizeChangedNotifier.Listener, VideoTrimFrameLayout.OnVideoScrollCallBack, CropCallback, HorizontalListView.OnScrollCallBack, Handler.Callback {
    public static final VideoDisplayMode SCALE_CROP = VideoDisplayMode.SCALE;
    public static final VideoDisplayMode SCALE_FILL = VideoDisplayMode.FILL;
    private String videoPath;
    private ActivityShareVideoCompileBinding binding;
    private int screenWidth;
    private VideoSliceSeekBar seekBar;
    private AliyunICrop crop;
    private long duration;
    private HorizontalListView listView;
    private VideoTrimAdapter adapter;
    private long mStartTime;
    private long mEndTime;
    private AliyunIThumbnailFetcher mThumbnailFetcher;
    private VideoTrimFrameLayout frame;
    private TextureView surfaceview;
    private int videoWidth;
    private int videoHeight;
    private int frameWidth;
    private int frameHeight;
    private int mScrollX;
    private int mScrollY;
    private boolean isCropping = false;
    private static final int PLAY_VIDEO = 1000;
    private static final int PAUSE_VIDEO = 1001;
    private static final int END_VIDEO = 1003;
    private VideoQuality quality = VideoQuality.HD;
    private VideoCodecs mVideoCodec = VideoCodecs.H264_HARDWARE;
    private VideoDisplayMode cropMode = VideoDisplayMode.SCALE;
    private Handler playHandler = new Handler(this);
    private int mAction = CropKey.ACTION_TRANSCODE;
    private String outputPath;
    private boolean needPlayStart = false;
    private AliyunISVideoPlayer mPlayer;
    private Surface mSurface;
    private int playState = END_VIDEO;
    private boolean isPause = false;
    private int cropDuration = 6*1000;
    private ImageView start2;

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_share_video_compile);
        screenWidth = getResources().getDisplayMetrics().widthPixels;
        videoPath = getIntent().getStringExtra("videoPath");
        crop = AliyunCropCreator.createCropInstance(this);
        crop.setCropCallback(this);
        try {
            duration = crop.getVideoDuration(videoPath) / 1000;
        } catch (Exception e) {
            e.printStackTrace();
        }
        initDataView();
        initSurface();
    }

    //初始化view
    private void initDataView() {
        start2 = (ImageView) findViewById(R.id.start2);
        seekBar = (VideoSliceSeekBar) findViewById(R.id.seek_bar);
        seekBar.setSeekBarChangeListener(mSeekBarListener);
        int minDiff = (int) (cropDuration / (float) duration * 100) + 1;
        seekBar.setProgressMinDiff(minDiff > 100 ? 100 : minDiff);
        listView = (HorizontalListView) findViewById(R.id.image_list);
        listView.setOnScrollCallBack(this);

        binding.backView.setOnClickListener(this);
        binding.nextStep.setOnClickListener(this);
        binding.start2.setOnClickListener(this);
        binding.tvTimes.setText("已选取" + Float.valueOf(duration/1000).intValue() + "s");
        setListViewHeight();
        adapter = new VideoTrimAdapter(this, new ArrayList<SoftReference<Bitmap>>(),seekBar);
        listView.setAdapter(adapter);
        requestThumbItemTime();
    }

    private void setListViewHeight() {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) listView.getLayoutParams();
      //  layoutParams.height = (screenWidth - DensityUtils.dip2px(this, 40)) / 10;
     //   Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.video_icon_sweep_left);
       // layoutParams.height = DensityUtils.dip2px(this, 80);
        layoutParams.height = seekBar.getResSweepLeftHeight();
        listView.setLayoutParams(layoutParams);
        seekBar.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, layoutParams.height));
    }

    private void initSurface() {
        frame = (VideoTrimFrameLayout) findViewById(R.id.frame);
        frame.setOnSizeChangedListener(this);
        frame.setOnScrollCallBack(this);
        surfaceview = (TextureView) findViewById(R.id.video_surfaceview);
        resizeFrame();
        surfaceview.setSurfaceTextureListener(this);
    }

    private void resizeFrame() {
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) frame.getLayoutParams();
        layoutParams.width = screenWidth;
        layoutParams.height =  getWindowManager().getDefaultDisplay().getHeight();
        frame.setLayoutParams(layoutParams);
        NativeParser parser = new NativeParser();
        parser.init(videoPath);
        try {
            videoWidth = Integer.parseInt(parser.getValue(NativeParser.VIDEO_WIDTH));
            videoHeight = Integer.parseInt(parser.getValue(NativeParser.VIDEO_HEIGHT));

        } catch (NumberFormatException ex) {
            return;
        } finally {
            parser.release();
            parser.dispose();
        }

        if (videoWidth == 0 || videoHeight == 0) {
            return;
        }

        frameWidth = layoutParams.width;
        frameHeight = layoutParams.height;
        if (cropMode == SCALE_CROP) {
            scaleCrop(videoWidth, videoHeight);
        } else if (cropMode == SCALE_FILL) {
            scaleFill(videoWidth, videoHeight);
        }
    }

    private void scaleFill(int videoWidth, int videoHeight) {
        if (videoWidth == 0 || videoHeight == 0) {
            return;
        }
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) surfaceview.getLayoutParams();
        int s = Math.min(videoWidth, videoHeight);
        int b = Math.max(videoWidth, videoHeight);
        float videoRatio = (float) b / s;
        float ratio = 1f;
        ratio = (float) 16 / 9;
        if (videoWidth > videoHeight) {
            layoutParams.width = frameWidth;
            layoutParams.height = frameWidth * videoHeight / videoWidth;
        } else {
            if (videoRatio >= ratio) {
                layoutParams.height = frameHeight;
                layoutParams.width = frameHeight * videoWidth / videoHeight;
            } else {
                layoutParams.width = frameWidth;
                layoutParams.height = frameWidth * videoHeight / videoWidth;
            }
        }
        layoutParams.setMargins(0, 0, 0, 0);
        surfaceview.setLayoutParams(layoutParams);
        cropMode = SCALE_FILL;
        binding.nextStep.setActivated(false);
        resetScroll();
    }

    private void scaleCrop(int videoWidth, int videoHeight) {
        if (videoWidth == 0 || videoHeight == 0) {
            return;
        }
        FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) surfaceview.getLayoutParams();
        int s = Math.min(videoWidth, videoHeight);
        int b = Math.max(videoWidth, videoHeight);
        float videoRatio = (float) b / s;
        float ratio;
        ratio = (float) 16 / 9;
        //原比例显示逻辑和填充模式一致
        if (videoWidth > videoHeight) {
            layoutParams.width = frameWidth;
            layoutParams.height = frameWidth * videoHeight / videoWidth;
        } else {
            if (videoRatio >= ratio) {
                layoutParams.height = frameHeight;
                layoutParams.width = frameHeight * videoWidth / videoHeight;
            } else {
                layoutParams.width = frameWidth;
                layoutParams.height = frameWidth * videoHeight / videoWidth;
            }
        }
        layoutParams.setMargins(0, 0, 0, 0);
        surfaceview.setLayoutParams(layoutParams);
        cropMode = SCALE_CROP;
        binding.nextStep.setActivated(true);
        resetScroll();
    }

    private void resetScroll() {
        mScrollX = 0;
        mScrollY = 0;
    }

    /**
     * 获取每个item取帧的时间值
     **/
    private void requestThumbItemTime() {
        int itemWidth = screenWidth / 10;
        mThumbnailFetcher = AliyunThumbnailFetcherFactory.createThumbnailFetcher();
        mThumbnailFetcher.addVideoSource(videoPath, 0, Integer.MAX_VALUE, 0);
        mThumbnailFetcher.setParameters(itemWidth, seekBar.getResSweepLeftHeight(), AliyunIThumbnailFetcher.CropMode.Mediate, VideoDisplayMode.SCALE, 10);
        long duration = mThumbnailFetcher.getTotalDuration();
        long itemTime = duration / 10;
        for (int i = 1; i <= 10; i++) {
            requestFetchThumbnail(itemTime, i, 10);
        }
    }

    /**
     * 获取缩略图
     *
     * @param interval 取帧平均间隔
     * @param position 第几张
     * @param count    总共的张数
     */
    private void requestFetchThumbnail(final long interval, final int position,
                                       final int count) {
        long[] times = {(position - 1) * interval + interval / 2};
        mThumbnailFetcher.requestThumbnailImage(times, new AliyunIThumbnailFetcher.OnThumbnailCompletion() {
            private int vecIndex = 1;

            @Override
            public void onThumbnailReady(Bitmap frameBitmap, long l) {
                if (frameBitmap != null && !frameBitmap.isRecycled()) {
                    SoftReference<Bitmap> bitmapSoftReference = new SoftReference<Bitmap>(frameBitmap);
                    adapter.add(bitmapSoftReference);
                } else {
                    if (position == 0) {
                        vecIndex = 1;
                    } else if (position == count + 1) {
                        vecIndex = -1;
                    }
                    int np = position + vecIndex;
                    requestFetchThumbnail(interval, np, count);
                }
            }

            @Override
            public void onError(int errorCode) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back_view) {//返回放弃编辑
            showDialog();
        } else if (id == R.id.start2) {//暂停
            if (mPlayer != null) {
                playVideo();
            }
        } else if (id == R.id.next_step) {//下一步
            nextStepData();
        }
    }

    private void nextStepData() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.System.canWrite(getApplicationContext())) {
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            } else {
                //有了权限，具体的动作
                DialogHelper.showProgressDialog(ShareVideoCompileActivity.this, null, "生成视频中...", 0, false, null).setCanceledOnTouchOutside(false);
                if (mScrollX != 0 || mScrollY != 0 || !cropMode.equals(cropMode)) {
                    //需要裁剪画面时或者切换裁剪模式时，走真裁剪
                    mAction = CropKey.ACTION_TRANSCODE;
                }
                long duration = mEndTime - mStartTime;
                switch (mAction) {
                    case CropKey.ACTION_TRANSCODE:
                        if (duration > 60 * 1000) {
                            DialogHelper.dismissProgressDialog();
                            MToast.showToast(getApplicationContext(), "裁剪视频不能超过一分钟！");
                            return;
                        } else {
                            if (duration > 5) {
                                startCrop();
                            } else {
                                DialogHelper.dismissProgressDialog();
                                MToast.showToast(getApplicationContext(), "裁剪视频不能小于6s！");
                                return;
                            }
                        }
                        break;
                    case CropKey.ACTION_SELECT_TIME:
                        if (duration > 60 * 1000) {
                            DialogHelper.dismissProgressDialog();
                            MToast.showToast(getApplicationContext(), "裁剪视频不能超过一分钟！");
                            return;
                        } else {
                            if (duration > 5) {
                                CropOutputParam cropOutputParam = new CropOutputParam();
                                //由于只是选择时间，所以文件路径和输入路径保持一致
                                cropOutputParam.setOutputPath(videoPath);
                                cropOutputParam.setDuration(duration);
                                cropOutputParam.setStartTime(mStartTime);
                                onCropComplete(cropOutputParam);
                            } else {
                                DialogHelper.dismissProgressDialog();
                                MToast.showToast(getApplicationContext(), "裁剪视频不能小于6s！");
                                return;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    private void startCrop() {
        if (!PermissionUtils.checkPermissionsGroup(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})) {
            MToast.showToast(this, PermissionUtils.NO_PERMISSION_TIP[4]);
            DialogHelper.dismissProgressDialog();
            return;
        }
        if (frameWidth == 0 || frameHeight == 0) {
            isCropping = false;
            return;
        }
        if (isCropping) {
            return;
        }
        //开始裁剪时，暂停视频的播放,提高裁剪效率
        pauseVideo();
        final FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) surfaceview.getLayoutParams();
        int posX;
        int posY;
        int outputWidth = 0;
        int outputHeight = 0;
        int cropWidth;
        int cropHeight;
        outputPath = ShareConstants.SDCardConstants.getDir(this) + DateUtils.getDateTimeFromMillisecond(System.currentTimeMillis()) + ShareConstants.SDCardConstants.CROP_SUFFIX;
        float videoRatio = (float) videoHeight / videoWidth;
        float outputRatio = 1f;
        outputRatio = videoRatio;
        if (videoRatio > outputRatio) {
            posX = 0;
            posY = ((lp.height - frameHeight) / 2 + mScrollY) * videoWidth / frameWidth;
            while (posY % 4 != 0) {
                posY++;
            }
            outputWidth = 720;
            cropWidth = videoWidth;
            cropHeight = 0;
        } else if (videoRatio < outputRatio) {
            posX = ((lp.width - frameWidth) / 2 + mScrollX) * videoHeight / frameHeight;
            posY = 0;
            while (posX % 4 != 0) {
                posX++;
            }
            outputWidth = 720;
            cropHeight = videoHeight;
            cropWidth = (int) (videoHeight / videoRatio);
            outputHeight = (int) (outputWidth * videoRatio);
        } else {
            // 原比例或videoRatio = outputRatio执行else
            posX = 0;
            posY = 0;
            outputWidth = 720;
            cropHeight = videoHeight;
            cropWidth = (int) (videoHeight / videoRatio);
            outputHeight = (int) (outputWidth * videoRatio);
        }
        CropParam cropParam = new CropParam();
        cropParam.setOutputPath(outputPath);
        cropParam.setInputPath(videoPath);
        cropParam.setOutputWidth(outputWidth);
        cropParam.setOutputHeight(outputHeight);
        Rect cropRect = new Rect(posX, posY, posX + cropWidth, posY + cropHeight);
        cropParam.setCropRect(cropRect);
        cropParam.setStartTime(mStartTime * 1000);
        cropParam.setEndTime(mEndTime * 1000);
        cropParam.setScaleMode(cropMode);
        cropParam.setFrameRate(30);
        cropParam.setGop(250);
        cropParam.setQuality(quality);
        cropParam.setVideoCodec(mVideoCodec);
        cropParam.setFillColor(Color.BLACK);
        cropParam.setCrf(0);
        cropParam.setUseGPU(false);
        crop.setCropParam(cropParam);
        int ret = crop.startCrop();
        if (ret < 0) {
            return;
        }
        isCropping = true;
        seekBar.setSliceBlocked(true);
    }

    private void pauseVideo() {
        if (mPlayer == null) {
            return;
        }
        mPlayer.pause();
        start2.setVisibility(View.VISIBLE);
        playState = PAUSE_VIDEO;
        playHandler.removeMessages(PLAY_VIDEO);
        seekBar.showFrameProgress(false);
        seekBar.invalidate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isPause) {
            playVideo();
        }
        if (isCropping && mPlayer != null) {
            long currentPosition = mPlayer.getCurrentPosition() / 1000;
            mPlayer.draw(currentPosition);
        }
    }

    @Override
    protected void onPause() {
        if (playState == PLAY_VIDEO) {
            pauseVideo();
        }
        isPause = true;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (crop != null) {
            crop.dispose();
            crop = null;
        }
        if (mThumbnailFetcher != null) {
            mThumbnailFetcher.release();
        }
    }

    //提示弹窗
    private void showDialog() {
        View view = View.inflate(ShareVideoCompileActivity.this, R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(ShareVideoCompileActivity.this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("温馨提示");
        TextView tv_logout_cancel = (TextView) view.findViewById(R.id.tv_logout_cancel);
        TextView tv_logout_confirm = (TextView) view.findViewById(R.id.tv_logout_confirm);
        tv_message.setText("是否放弃此次编辑？");
        tv_logout_confirm.setTextColor(getApplicationContext().getResources().getColor(R.color.color_5792FD));
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                crop.cancel();
                roundCornerDialog.dismiss();
                finish();
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    private void playVideo() {
        if (isCropping) {
            //裁剪过程中点击无效
            return;
        }
        if (mPlayer == null) {
            return;
        }
        mPlayer.seek((int) mStartTime);
        mPlayer.resume();
        start2.setVisibility(View.GONE);
        playState = PLAY_VIDEO;
        playHandler.sendEmptyMessage(PLAY_VIDEO);
        //重新播放之后修改为false，防止暂停、播放的时候重新开始播放
        needPlayStart = false;
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case PAUSE_VIDEO:
                pauseVideo();
                break;
            case PLAY_VIDEO:
                if (mPlayer != null) {
                    long currentPlayPos = mPlayer.getCurrentPosition() / 1000;
                    if (currentPlayPos < mEndTime) {
                        seekBar.showFrameProgress(true);
                        seekBar.setFrameProgress(currentPlayPos / (float) duration);
                        playHandler.sendEmptyMessageDelayed(PLAY_VIDEO, 100);
                    } else {
                        playVideo();
                    }
                }
                break;
            default:
                break;
        }
        return false;
    }

    @Override
    public void onScrollDistance(Long count, int distanceX) {

    }

    @Override
    public void onProgress(int i) {
    }

    @Override
    public void onError(int i) {
        isCropping = false;
    }

    @Override
    public void onComplete(long l) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                seekBar.setSliceBlocked(false);
                scanFile();
                long duration = mEndTime - mStartTime;
                CropOutputParam cropOutputParam = new CropOutputParam();
                cropOutputParam.setOutputPath(outputPath);
                cropOutputParam.setDuration(duration);
                onCropComplete(cropOutputParam);
            }
        });
        isCropping = false;
    }

    /**
     * 裁剪结束
     */
    private void onCropComplete(CropOutputParam outputParam) {
        DialogHelper.dismissProgressDialog();
        //跳转到发布界面
        SharePublishActivity.start(ShareVideoCompileActivity.this, outputParam.getOutputPath(), 0, 2,0);
    }

    private void scanFile() {
        MediaScannerConnection.scanFile(getApplicationContext(),
                new String[]{outputPath}, new String[]{"video/mp4"}, null);
    }

    @Override
    public void onCancelComplete() {
        //取消完成
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                seekBar.setSliceBlocked(false);
            }
        });
        deleteFile();
        setResult(Activity.RESULT_CANCELED);
        finish();
        isCropping = false;
    }

    private void deleteFile() {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                FileUtils.deleteFile(outputPath);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    private VideoSliceSeekBar.SeekBarChangeListener mSeekBarListener = new VideoSliceSeekBar.SeekBarChangeListener() {
        @Override
        public void seekBarValueChanged(float leftThumb, float rightThumb, int whitchSide) {
            long seekPos = 0;
            if (whitchSide == 0) {
                seekPos = (long) (duration * leftThumb / 100);
                mStartTime = seekPos;
            } else if (whitchSide == 1) {
                seekPos = (long) (duration * rightThumb / 100);
                mEndTime = seekPos;
            }
            binding.tvTimes.setText("已选取" +  Float.valueOf((mEndTime - mStartTime) / 1000).intValue()+ "s");
            if (mPlayer != null) {
                mPlayer.seek((int) seekPos);
            }
        }

        @Override
        public void onSeekStart() {
            pauseVideo();
        }

        @Override
        public void onSeekEnd() {
            needPlayStart = true;
            if (playState == PAUSE_VIDEO) {
                playVideo();
            }
        }
    };

    @Override
    public void onVideoScroll(float distanceX, float distanceY) {
        if (isCropping) {
            //裁剪中无法操作
            return;
        }
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) surfaceview.getLayoutParams();
        int width = lp.width;
        int height = lp.height;

        if (width > frameWidth || height > frameHeight) {
            int maxHorizontalScroll = width - frameWidth;
            int maxVerticalScroll = height - frameHeight;
            if (maxHorizontalScroll > 0) {
                maxHorizontalScroll = maxHorizontalScroll / 2;
                mScrollX += distanceX;
                if (mScrollX > maxHorizontalScroll) {
                    mScrollX = maxHorizontalScroll;
                }
                if (mScrollX < -maxHorizontalScroll) {
                    mScrollX = -maxHorizontalScroll;
                }
            }
            if (maxVerticalScroll > 0) {
                maxVerticalScroll = maxVerticalScroll / 2;
                mScrollY += distanceY;
                if (mScrollY > maxVerticalScroll) {
                    mScrollY = maxVerticalScroll;
                }
                if (mScrollY < -maxVerticalScroll) {
                    mScrollY = -maxVerticalScroll;
                }
            }
            lp.setMargins(0, 0, mScrollX, mScrollY);
        }

        surfaceview.setLayoutParams(lp);
    }

    @Override
    public void onVideoSingleTapUp() {
        if (isCropping) {
            //裁剪过程中点击无效
            return;
        }
        if (playState == END_VIDEO) {
            playVideo();
        } else if (playState == PLAY_VIDEO) {
            pauseVideo();
        } else if (playState == PAUSE_VIDEO) {
            resumeVideo();
        }
    }

    private void resumeVideo() {
        if (mPlayer == null) {
            return;
        }
        if (needPlayStart) {
            playVideo();
            needPlayStart = false;
            return;
        }
        start2.setVisibility(View.GONE);
        mPlayer.resume();
        playState = PLAY_VIDEO;
        playHandler.sendEmptyMessage(PLAY_VIDEO);
    }


    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
        if (mPlayer == null) {
            mSurface = new Surface(surface);
            mPlayer = AliyunSVideoPlayerCreator.createPlayer();
            mPlayer.init(this);

            mPlayer.setPlayerCallback(new PlayerCallback() {
                @Override
                public void onPlayComplete() {

                }

                @Override
                public void onDataSize(int dataWidth, int dataHeight) {
                    if (dataWidth == 0 || dataHeight == 0) {
                        return;
                    }
                    frameWidth = frame.getWidth();
                    frameHeight = frame.getHeight();
                    videoWidth = dataWidth;
                    videoHeight = dataHeight;
                    if (crop != null && mEndTime == 0) {
                        try {
                            mEndTime = (long) (crop.getVideoDuration(videoPath) * 1.0f / 1000);
                        } catch (Exception e) {
                        }
                    }

                    if (cropMode == SCALE_CROP) {
                        scaleCrop(dataWidth, dataHeight);
                    } else if (cropMode == SCALE_FILL) {
                        scaleFill(dataWidth, dataHeight);
                    }
                    mPlayer.setDisplaySize(surfaceview.getLayoutParams().width, surfaceview.getLayoutParams().height);
                    playVideo();

                }

                @Override
                public void onError(int i) {


                }
            });
            mPlayer.setDisplay(mSurface);
            mPlayer.setSource(videoPath);

        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
        mPlayer.setDisplaySize(width, height);
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            playState = END_VIDEO;
            mPlayer = null;
            mSurface.release();
            mSurface = null;
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) {

    }

    @Override
    public void onSizeChanged(View view, int w, int h, int oldw, int oldh) {

    }
}
